﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text.RegularExpressions;

namespace ProjectStudy
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string ip = GetIP();
                lbIP.Text = ip;
                //string region = IpLocation(ip);
                //lbRegion.Text = region;

            }
        }

        public string IpLocation(string ipAddress)
        {
            string[] result;
            if (string.IsNullOrEmpty(ipAddress.Trim()))
            {
                return null;
            }
            WebClient client = new WebClient();
            client.Encoding = System.Text.Encoding.GetEncoding("GB2312");
            string url = "http://www.ip138.com/ips.asp";
            string post = "ip=" + ipAddress + "&action=2";
            client.Headers.Set("Content-Type", "application/x-www-form-urlencoded");
            string response = client.UploadString(url, post);

            string p = @"<li>参考数据二：(?<location>[^<>]+?)</li>";
            Match match = Regex.Match(response, p);
            string m_Location = match.Groups["location"].Value.Trim();
            result = m_Location.Split(' ');
            return result[0];
        }

        public static string GetIP()
        {
            //如果客户端使用了代理服务器，则利用HTTP_X_FORWARDED_FOR找到客户端IP地址
            string userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ConvertObjToStr().Split(',')[0].ConvertObjToStr().Trim();
            //否则直接读取REMOTE_ADDR获取客户端IP地址
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ConvertObjToStr().Trim();
            }
            //前两者均失败，则利用Request.UserHostAddress属性获取IP地址，但此时无法确定该IP是客户端IP还是代理IP
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress.ConvertObjToStr().Trim();
            }
            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }  
    }
}